# -*- coding: utf-8 -*-

import pymongo
from bson import ObjectId
from bson.errors import InvalidId
from flask import render_template
from flask import request
from flask_restful import Resource
from flask_user import current_user, login_required
from webargs import fields
from webargs.flaskparser import use_args

from tank import api, app
from ammunition.note.documents import Book, Note
from .. import bp


@app.route("/noteBoard", endpoint="noteBoard")
@login_required
def home_view():
    return render_template('dev/note.html')


@api.resource('/book', '/book/<string:oid>')
class BookResource(Resource):
    def get(self, oid=None):
        if not oid:
            return Book.find({'owner': current_user.id, "_delete": False}).sort([('dateCreated', pymongo.DESCENDING)])

        note_fields = {
            'bookId': 1,
            'title': 1,
            'dateUpdated': 1,
            '_delete': 1,
            'isPublished': 1
        }
        if oid == 'recent':
            book = {
                '_id': 'recent',
                'name': 'recent',
                'notes': Note.find({
                    'owner': current_user.id, "_delete": False
                }, note_fields).sort([('dateUpdated', pymongo.DESCENDING)])
            }
        elif oid == 'recycle':
            book = {
                '_id': 'recycle',
                'name': 'recycle',
                'notes': Note.find({
                    'owner': current_user.id, "_delete": True
                }, note_fields).sort([('dateUpdated', pymongo.DESCENDING)])
            }
        else:
            book = Book.find_by_oid(oid)
            book['notes'] = Note.find({
                'bookId': book.oid, "_delete": False
            }, note_fields).sort([('dateUpdated', pymongo.DESCENDING)])
        return book

    def post(self):
        name = request.json.get('name')
        if Book.find_one({'owner': current_user.id, 'name': name, "_delete": False}):
            raise UserWarning('Book named "%s" is exists!'.format(name))
        book = Book()
        book['name'] = name
        book['owner'] = current_user.id
        book.save()
        return book

    @use_args({
        'name': fields.Str(),
        'isPublished': fields.Boolean(),
    })
    def put(self, args, oid):
        book = Book.find_by_oid(oid)
        book.save(args)
        if "isPublished" in args:
            Note.update_many({"_delete": False, 'bookId': book.oid}, {'$set': {"isPublished": args['isPublished']}})
        return book

    def delete(self, oid):
        book = Book.find_by_oid(oid)
        if book:
            book.save({"_delete": True})
            Note.update_many({"_delete": False, 'bookId': book.oid}, {'$set': {"_delete": True}})
        return {}


@api.resource('/note', '/note/<string:oid>')
class NoteResource(Resource):
    def get(self, oid=Note):
        if not oid:

            selector = {'owner': current_user.id, "_delete": False}
            if 'bookId' in request.args:
                selector['bookId'] = ObjectId(request.args.get("bookId"))
            return Note.find(selector).sort([('dateUpdated', pymongo.DESCENDING)])

        return Note.find_by_oid(oid)

    def post(self):
        title = request.form.get('title')
        content = request.form.get('content')
        bookId = request.form.get('bookId')
        ext = request.form.get('ext')

        note = Note()
        note['title'] = title
        note['content'] = content
        note['owner'] = current_user.id
        note['ext'] = ext
        try:
            note['bookId'] = ObjectId(bookId)
        except InvalidId as e:
            note['bookId'] = None
        note.save()
        return note

    def put(self, oid):
        note = Note.find_by_oid(oid)
        title = request.form.get('title', note['title'])
        content = request.form.get('content', note['content'])
        bookId = request.form.get("bookId", note.book_id)
        note.save({'title': title,
                   'content': content,
                   '_delete': False,
                   'bookId': ObjectId(str(bookId)) if ObjectId.is_valid(bookId) else None})
        return note

    def delete(self, oid):
        note = Note.find_by_oid(oid)
        force = request.json.get('force')
        if note:
            if force:
                note.remove()
            else:
                note.save({"_delete": True})
        return {}
